package com.fwj.core.common.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.OSSObject;
import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.ResponseEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: fwj
 * @Data: 2022/4/15 0:08
 * @Version 1.0
 * @Description:    阿里云文件上传服务
 */

public class OSSFileUtils {

    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(OSSFileUtils.class);

    private static String config = "config";

    /**
     * 阿里云IP地址
     * */
    private static final String ENDPOINT = PropertiesFileUtil.getInstance(config).get("oss.endpoint");

    /**
     * 阿里云访问令牌ID
     */
    private static String ACCESS_KEY_ID = PropertiesFileUtil.getInstance(config).get("oss.accessKeyID");

    /**
     * 阿里云访问令牌密钥
     */
    private static String ACCESS_KEY_SECRET = PropertiesFileUtil.getInstance(config).get("oss.accessKeySecret");

    /**
     * 分配的阿里云路由
     */
    private static String PREFIX = PropertiesFileUtil.getInstance(config).get("oss.prefix");

    /**
     * 文件桶名称
     */
    private static String BUCKET_NAME = PropertiesFileUtil.getInstance(config).get("oss.bucketName");

    public static String upload(String fileName, InputStream inputStream) {
        String fileType = "";
        //获取文件类型
        if (fileName != null) {
            String[] split = fileName.split("\\.");
            fileType = split[split.length - 1];
        }
        //构建存储路径
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Long time = System.currentTimeMillis();
        String key = simpleDateFormat.format(time) + "/" + fileType + "/" + time + "/" + fileName;
        //创建OSS连接
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            //上传文件
            ossClient.putObject(BUCKET_NAME, key, inputStream);
            //返回存储路径
            return key;
        } catch (Exception e) {
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.FILE_UPLOAD_ERROR);
        } finally {
            if (null != ossClient){
                ossClient.shutdown();
            }
        }
    }

    public static void download(String location, HttpServletRequest request, HttpServletResponse response){
        InputStream is = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        OSS ossClient = null;
        OSSObject object = null;
        try {
            ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            object = ossClient.getObject(BUCKET_NAME, location);
            is = object.getObjectContent();
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(response.getOutputStream());
            String[] split = location.split("\\/");
            location = split[split.length - 1];
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                location = URLEncoder.encode(location, "UTF-8");
            } else {
                location = new String(location.getBytes("UTF-8"), "iso-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + location);
            byte[] buffer = new byte[1024];
            int L = 0;
            while ((L = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, L);
            }
            bos.flush();
        } catch (IOException e){
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        } finally {
            try {
                if (null != bos) {
                    bos.close();
                }
                if (null != bis) {
                    bis.close();
                }
                if (null != is) {
                    is.close();
                }
                if (null != object) {
                    object.close();
                }
                if (null != ossClient){
                    ossClient.shutdown();
                }
            } catch (IOException e){
                LOGGER.error(e.toString());
            }
        }
    }


    /**
     * 彻底删除OSS文件，不交由用户处理,手动或者定时处理
     * */
    public static List<String> delete(List<String> keys){
        OSS ossClient = null;
        DeleteObjectsRequest deleteObjectsRequest = null;
        DeleteObjectsResult deleteObjectsResult = null;
        try {
            ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            deleteObjectsRequest = new DeleteObjectsRequest(BUCKET_NAME);
            deleteObjectsRequest.setKeys(keys);
            deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
            List<String> deletedList = deleteObjectsResult.getDeletedObjects();
            return deletedList;
        } catch (Exception e){
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        } finally {
            if (null != ossClient){
                ossClient.shutdown();
            }
        }
    }

}
